<template>
  <el-dialog :title="title" :visible.sync="dialogShow" @close="closeDialog">
    <!-- 绘制表单 -->
    <el-form
      :model="formData"
      :rules="formRules"
      ref="form"
      label-width="180px"
    >
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="formData.name" style="width: 440px"></el-input>
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="formData.code" style="width: 440px"></el-input>
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select
          @focus="getEmployeeData"
          v-model="formData.manager"
          style="width: 440px"
          placeholder="请选择"
        >
          <!-- ⭐label：下拉列表显示的文字，value：将哪个字段的数据给select中v-model绑定变量 -->
          <el-option
            v-for="(item, index) in managerList"
            :key="index"
            :label="item.username"
            :value="item.username"
          ></el-option>
        </el-select>
        <!-- <el-input
          @focus="getEmployeeData"
          v-model="formData.manager"
          style="width: 380px"
        ></el-input> -->
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          rows="3"
          v-model="formData.introduce"
          style="width: 440px"
          type="textarea"
        ></el-input>
      </el-form-item>
      <el-row type="flex" justify="center">
        <!-- type="primary"按钮样式 -->
        <el-button size="small" type="primary" @click="btnOk">确定</el-button>
        <el-button size="small" @click="dialogShow = false">取消</el-button>
      </el-row>
    </el-form>
  </el-dialog>
</template>

<script>
import {
  editDepartmentApi,
  getDepartmentInfoApi,
  getDepartmentListApi,
  addDepartmentApi
} from '@/api/departments'
import { getEmployeeSimple } from '@/api/employees'
export default {
  name: 'AddDept',
  data() {
    // ⭐部门名称校验
    const CheckNameRepeat = async (valid, value, cb) => {
      // console.log(this.formData.pid)
      // 1.获取所有部门信息 => 部门名称
      const { depts } = await getDepartmentListApi()
      // console.log('depts', depts)
      // 2.筛选出当前部门的兄弟部门
      let arr = depts.filter((item) => item.pid === this.formData.pid)
      // ⭐编辑状态下 排除自己  // ⭐编辑时formData里会有回显数据
      if (this.formData.id) {
        arr = arr.filter((item) => item.id !== this.formData.id)
      }
      // 3.名称查重
      const isRepeat = arr.some((item) => item.name === value)
      isRepeat ? cb(new Error('名字重复了')) : cb()
    }
    // ⭐部门编码校验
    const CheckCodeRepeat = async (valid, value, cb) => {
      // 1.获取所有部门信息 => 部门编码
      let { depts } = await getDepartmentListApi()
      // ⭐编辑状态下 排除自己  // ⭐编辑时formData里会有回显数据
      if (this.formData.id) {
        depts = depts.filter((item) => item.id !== this.formData.id)
      }
      // 2.编码查重
      const isRepeat = depts.some((item) => item.code === value)
      isRepeat ? cb(new Error('编码重复了')) : cb()
    }

    return {
      // 弹框是否显示控制变量
      dialogShow: false,
      // 表单数据变量
      formData: {
        code: '',
        introduce: '',
        manager: '',
        name: '',
        pid: ''
      },
      // 表单验证规则
      formRules: {
        code: [
          { required: true, message: '请输入', trigger: 'blur' },
          { validator: CheckCodeRepeat, trigger: 'blur' }
        ],
        introduce: [{ required: true, message: '请输入', trigger: 'blur' }],
        manager: [{ required: true, message: '请输入', trigger: 'blur' }],
        name: [
          { required: true, message: '请输入', trigger: 'blur' },
          { validator: CheckNameRepeat, trigger: 'blur' }
        ]
      },
      // 负责人数据
      managerList: []
    }
  },
  computed: {
    title() {
      // ⭐修改时formData里会有回显数据
      return this.formData.id ? '修改' : '新增'
    }
  },
  methods: {
    // 提交事件逻辑
    async btnOk() {
      // 1.表单数据校验
      console.log(this.$refs.form)
      try {
        await this.$refs.form.validate()
      } catch (error) {
        return console.log(error)
      }
      // 2.发起对应(添加/修改)请求
      if (this.formData.id) {
        // 发edit请求
        await editDepartmentApi(this.formData)
        // 3.提示修改成功
        this.$message.success('修改成功')
      } else {
        // 发add请求
        await addDepartmentApi(this.formData)
        // 3.提示添加成功
        this.$message.success('添加成功')
      }

      // 4.更新列表
      this.$emit('updataList')
      // 5.关闭对话弹框,重置表单(关闭弹窗会有触发close事件)
      this.dialogShow = false
    },
    // 获得负责人数据
    async getEmployeeData() {
      const res = await getEmployeeSimple()
      // console.log('Employee', res)
      this.managerList = res
    },
    // 关闭dialog触发事件（叉号、黑色区域、取消按钮）
    closeDialog() {
      this.formData = {
        code: '',
        introduce: '',
        manager: '',
        name: '',
        pid: ''
      }
      // ⭐重置表单到初始状态 fprm实例对象clearValidate方法
      // console.log(this.$refs.form)
      this.$refs.form.clearValidate()
    },
    // 点击编辑时触发
    async getFormDataInfo(id) {
      const res = await getDepartmentInfoApi(id)
      // console.log(res)
      // 数据回显
      this.formData = res
      // 打开弹窗
      this.dialogShow = true
    }
  }
}
</script>

<style></style>
